import { View, Text, Image } from '@tarojs/components'
import { useState, useEffect } from 'react'
import { 
  Card, 
  Button
} from '@nutui/nutui-react-taro'
import Taro, { useLoad, useDidShow } from '@tarojs/taro'
import { serviceApi, userApi } from '../../api/index'
import './index.less'

export default function Index() {
  const [userInfo, setUserInfo] = useState(null)
  const [services, setServices] = useState([])
  const [loading, setLoading] = useState(false)

  // 优惠活动数据
  const promotions = [
    {
      id: 1,
      type: 'new',
      title: '新用户专享',
      subtitle: '首次下单立减20元',
      description: '所有洗护服务均可使用',
      buttonText: '立即领取',
      color: 'linear-gradient(135deg, #ff6b9d 0%, #ff8a80 100%)',
      textColor: '#fff'
    },
    {
      id: 2,
      type: 'member',
      title: '会员专享',
      subtitle: '满100减30',
      description: '会员专享优惠',
      buttonText: '立即领取',
      color: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
      textColor: '#fff'
    }
  ]

  // 服务类型数据
  const serviceTypes = [
    {
      id: 1,
      icon: '👔',
      name: '衣物清洗',
      color: '#4facfe'
    },
    {
      id: 2,
      icon: '💰',
      name: '鞋子洗护',
      color: '#43e97b'
    },
    {
      id: 3,
      icon: '👕',
      name: '干洗服务',
      color: '#fa709a'
    }
  ]

  // 快捷预约数据
  const quickBooking = [
    {
      id: 1,
      icon: '🚚',
      title: '上门取送',
      subtitle: '足不出户，轻松洗护',
      buttonText: '立即预约',
      buttonColor: '#4facfe'
    },
    {
      id: 2,
      icon: '🏪',
      title: '到店服务',
      subtitle: '附近门店，立等可取',
      buttonText: '查找门店',
      buttonColor: '#43e97b'
    }
  ]

  useLoad(() => {
    checkLogin()
    loadServices()
  })

  useDidShow(() => {
    checkLogin()
  })

  const checkLogin = async () => {
    try {
      const user = Taro.getStorageSync('userInfo')
      setUserInfo(user)
      
      if (user) {
        try {
          const userData = await userApi.getUserInfo()
          setUserInfo(userData)
          Taro.setStorageSync('userInfo', userData)
        } catch (error) {
          console.log('获取用户信息失败:', error)
        }
      }
    } catch (error) {
      console.log('获取本地用户信息失败')
    }
  }

  const loadServices = async () => {
    try {
      setLoading(true)
      const serviceData = await serviceApi.getServiceList()
      setServices(serviceData || [])
    } catch (error) {
      console.log('获取服务列表失败:', error)
      setServices([])
    } finally {
      setLoading(false)
    }
  }

  const handlePromotion = (promotion) => {
    if (!userInfo) {
      Taro.showToast({
        title: '请先登录',
        icon: 'none'
      })
      setTimeout(() => {
        Taro.navigateTo({ url: '/pages/login/index' })
      }, 1500)
      return
    }

    Taro.showToast({
      title: '优惠券领取成功',
      icon: 'success'
    })
  }

  const handleServiceType = (service) => {
    if (!userInfo) {
      Taro.showToast({
        title: '请先登录',
        icon: 'none'
      })
      setTimeout(() => {
        Taro.navigateTo({ url: '/pages/login/index' })
      }, 1500)
      return
    }
    
    Taro.navigateTo({ 
      url: `/pages/booking/index?serviceType=${service.name}` 
    })
  }

  const handleQuickBooking = (booking) => {
    if (!userInfo) {
      Taro.showToast({
        title: '请先登录',
        icon: 'none'
      })
      setTimeout(() => {
        Taro.navigateTo({ url: '/pages/login/index' })
      }, 1500)
      return
    }

    if (booking.id === 1) {
      // 上门取送
      Taro.navigateTo({ url: '/pages/booking/index?type=pickup' })
    } else {
      // 到店服务
      Taro.navigateTo({ url: '/pages/store-map/index' })
    }
  }

  const handleMorePromotions = () => {
    Taro.navigateTo({ url: '/pages/promotions/index' })
  }


  return (
    <View className='index-page'>
      {/* 优惠活动区域 */}
      <View className='promotions-section'>
        <View className='section-header'>
          <Text className='section-title'>优惠活动</Text>
          <Text className='more-link' onClick={handleMorePromotions}>更多活动</Text>
        </View>
        
        <View className='promotions-list'>
          {promotions.map(promotion => (
            <View 
              key={promotion.id}
              className='promotion-card'
              style={{ background: promotion.color }}
              onClick={() => handlePromotion(promotion)}
            >
              <View className='promotion-content'>
                <Text className='promotion-type'>{promotion.title}</Text>
                <Text className='promotion-title'>{promotion.subtitle}</Text>
                <Text className='promotion-desc'>{promotion.description}</Text>
                <Button 
                  className='promotion-btn'
                  size='small'
                  onClick={() => handlePromotion(promotion)}
                >
                  {promotion.buttonText}
                </Button>
              </View>
            </View>
          ))}
        </View>
      </View>

      {/* 服务类型区域 */}
      <View className='services-section'>
        <Text className='section-title'>服务类型</Text>
        
        <View className='services-grid'>
          {serviceTypes.map(service => (
            <View 
              key={service.id}
              className='service-item'
              onClick={() => handleServiceType(service)}
            >
              <View 
                className='service-icon'
                style={{ backgroundColor: service.color }}
              >
                <Text className='icon-text'>{service.icon}</Text>
              </View>
              <Text className='service-name'>{service.name}</Text>
            </View>
          ))}
        </View>
      </View>

      {/* 快捷预约区域 */}
      <View className='booking-section'>
        <Text className='section-title'>快捷预约</Text>
        
        <View className='booking-list'>
          {quickBooking.map(booking => (
            <View 
              key={booking.id}
              className='booking-item'
              onClick={() => handleQuickBooking(booking)}
            >
              <View className='booking-icon'>
                <Text className='icon-text'>{booking.icon}</Text>
              </View>
              <View className='booking-content'>
                <Text className='booking-title'>{booking.title}</Text>
                <Text className='booking-subtitle'>{booking.subtitle}</Text>
              </View>
              <Button 
                className='booking-btn'
                size='small'
                style={{ backgroundColor: booking.buttonColor }}
                onClick={() => handleQuickBooking(booking)}
              >
                {booking.buttonText}
              </Button>
            </View>
          ))}
        </View>
      </View>

    </View>
  )
}